﻿using CSCSN.EntitiyModels;
using CSCSN.ORM;
using CSCSN.ViewModels.RoleAndUser;
using CSCSN.ViewModelServices;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CSCSN.WebApplication.ViewComponents
{
    /// <summary>
    /// 登陆状态视图组件
    /// </summary>
        public class LoginViewComponent : ViewComponent
        {
            private readonly IViewModelService<ApplicationUser, ApplicationUserVM> _service;
            private readonly CsDbContext db;

            public LoginViewComponent(IViewModelService<ApplicationUser, ApplicationUserVM> service, CsDbContext logger)
            {
                _service = service;
                db = logger;
            }

            public async Task<IViewComponentResult> InvokeAsync()
            {
                var item = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
                var userName = "";
                var userDisplayName = "";
                var userAvatarPath = " ";
                if (item != null)
                {
                    var a = item.Id;
                    var id = db.ApplicationUserDatas.Where(s => s.ApplicationUsers.Id == a).FirstOrDefault();
                    if (id==null)
                    {
                    userAvatarPath = "/Photo/0.jpg";
                    
                    }
                    else
                    {
                    userAvatarPath = id.HeadPortrait;
                    }  
                    var userIdentity = User.Identity;
                    if (!String.IsNullOrEmpty(userIdentity.Name))
                    {
                        var user = await _service.EntityRepository.ApplicationUserManager.FindByNameAsync(userIdentity.Name);
                        //var userImage = await _service.EntityRepository.GetOtherBoAsyn<BusinessImage>(x => x.RelevanceObjectID == user.Id);
                        //if (userImage != null)
                        //    userAvatarPath = userImage.UploadPath;
                        userName = user.UserName;
                        userDisplayName = user.Name;
                    }
                }
                ViewData["LoginUserAvatarPath"] = userAvatarPath;
                ViewData["LoginUserName"] = userName;
                ViewData["LoginUserDisplayName"] = userDisplayName;
                return View("View");
            }
        }
    }